import { Body, Controller, Delete, Get, HttpException, HttpStatus, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Authorities } from 'src/decorators/authorities.decorator';
import { AuthoritiesGuard } from 'src/guards/authorities.guard';
import { Guard } from 'src/modules/guard/constants/guard.constant';
import { LantUtil } from '../../../../utils/lant.util';
import { CountResDto } from '../../../common/dtos/count.res.dto';
import { IdListReqDto } from '../../../common/dtos/id-list.req.dto';
import { LogAppender } from '../../constants/log.constant';
import { GetSystemLogAdminReqDto } from '../../dtos/system/admin/get-system-log.admin.req.dto';
import { GetSystemLogAdminResDto } from '../../dtos/system/admin/get-system-log.admin.res.dto';
import { LogService } from '../../services/log.service';

@ApiBearerAuth()
@ApiTags('logs')
@Controller('admin/logs')
export class LogAdminController {
  constructor(private readonly logService: LogService, private readonly lantUtil: LantUtil) {}

  @ApiOperation({ summary: '批量删除日志' })
  @ApiOkResponse({ description: '返回删除结果', type: CountResDto })
  @Authorities(Guard.SystemLogManage)
  @UseGuards(AuthGuard(), AuthoritiesGuard)
  @Delete()
  async deleteAll(@Body() body: IdListReqDto): Promise<CountResDto> {
    try {
      const deleteResult = await this.logService.deleteAll(body.id_list);

      return { count: deleteResult.affected };
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.fatal(LogAppender.log, `Cannot delete system log list by ${JSON.stringify(body)}, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @ApiOperation({ summary: '获取系统日志列表' })
  @ApiOkResponse({ description: '系统日志列表', type: GetSystemLogAdminResDto })
  @Authorities(Guard.SystemLogManage, Guard.SystemLogView)
  @UseGuards(AuthGuard(), AuthoritiesGuard)
  @Get()
  async getSystemLogList(@Query() query: GetSystemLogAdminReqDto): Promise<GetSystemLogAdminResDto> {
    try {
      const [logList, count] = await this.logService.findAndPaging(query.page_index, query.page_size, query.sort_type, query.start, query.end, query.level, query.appender, query.keyword);

      return {
        total_count: count,
        data: logList?.map(log => {
          return {
            id: log.id,
            level: log.level,
            appender: log.appender,
            message: log.message,
            detail: log.detail,
            created_at: log.createdAt
          };
        })
      };
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.fatal(LogAppender.log, `Cannot get system log list by ${JSON.stringify(query)}, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
